/*
 * Copyright (c) 2013, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.syncomponents.client;

import java.io.IOException;

import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.sunkey.log.util.JsonMapper;
import com.syncomponents.util.BaseConstant;
import commonj.sdo.DataObject;
import commonj.sdo.helper.XMLDocument;
import commonj.sdo.helper.XMLHelper;

/**
 * 实体类转换工具
 * 
 * @author sunkey
 * @date Mar 26, 2014
 */
public class MessageHelper {

    public static DataObject toDataObject(final HttpEntity entity) throws IOException, ClassNotFoundException {
        String msg = toString(entity);
        XMLDocument xmlDoc = XMLHelper.INSTANCE.load(msg);
        return xmlDoc.getRootObject();
    }

    public static DataObject toDataObject(final TextMessage message) throws ClassNotFoundException, JMSException {
        String msg = toString(message);
        XMLDocument xmlDoc = XMLHelper.INSTANCE.load(msg);
        return xmlDoc.getRootObject();
    }

    public static DataObject toDataObject(final String message) throws ClassNotFoundException, JMSException {
        XMLDocument xmlDoc = XMLHelper.INSTANCE.load(message);
        return xmlDoc.getRootObject();
    }

    public static String toString(final TextMessage message) throws ClassNotFoundException, JMSException {
        String msg = message.getText();
        return msg;
    }

    public static String toString(final HttpEntity entity) throws IOException, ClassNotFoundException {
        String msg = EntityUtils.toString(entity, BaseConstant.ENCODE_TYPE_UTF8);
        return msg;
    }

    public static byte[] toByteArray(final HttpEntity entity) throws IOException, ClassNotFoundException {
        byte[] msg = EntityUtils.toByteArray(entity);
        return msg;
    }

    public static <T> T toObjectForJson(final HttpEntity entity, Class<T> clazz) throws IOException,
            ClassNotFoundException {
        return JsonMapper.nonDefaultMapper().fromJson(toString(entity), clazz);
    }

    public static <T> T toObjectForJson(final String content, Class<T> clazz) throws IOException,
            ClassNotFoundException {
        return JsonMapper.nonDefaultMapper().fromJson(content, clazz);
    }

}
